package com.ease.web.struts2;

import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.ease.common.vo.Pagination;
import com.ease.common.vo.PaginationUrlParam;
import com.opensymphony.xwork2.ActionContext;

/**
 * 
 * @author nathanleewei
 * 
 */
public abstract class PaginationUtil {

	public static final String PAGINATION_INDEX = "pagination.index";

	public static final String PAGINATION_COUNT = "pagination.count";

	public static final String PAGINATION_COUNTED = "pagination.counted";

	public static final String PAGINATION_SIZE = "pagination.size";

	public static final String PAGINATION_KEYWORDS = ",pagination.index,pagination.count,pagination.counted,pagination.size,";

	public static PaginationUrlParam buildPaginationUrlParam(Pagination<?> pagination) throws Exception {
		PaginationUrlParam paginationUrlParam = new PaginationUrlParam();

		StringBuffer url = ServletActionContext.getRequest().getRequestURL();
		Map<String, Object> parameters = ActionContext.getContext().getParameters();
		if (null != parameters && parameters.size() > 0) {
			url.append("?");
			//
			Iterator<String> iterator = parameters.keySet().iterator();
			//
			String key = null;
			String[] values = null;
			//
			while (iterator.hasNext()) {
				key = (String) iterator.next();
				if (PAGINATION_KEYWORDS.indexOf("," + key + ",") < 0) {
					values = (String[]) parameters.get(key);
					for (int i = 0; i < values.length; i++) {
						// chinese charactors
						url.append(key).append("=").append(URLEncoder.encode(values[i], "UTF-8")).append("&");
					}
				}
			}

			key = null;
			values = null;

			url.append("&").append(PAGINATION_COUNT).append("=").append(pagination.getCount());
			url.append("&").append(PAGINATION_COUNTED).append("=").append(pagination.isCounted());
			url.append("&").append(PAGINATION_SIZE).append("=").append(pagination.getSize());

			StringBuffer sb = null;
			if (pagination.getIndex() > 1) {
				sb = new StringBuffer().append(url);
				sb.append("&").append(PAGINATION_INDEX).append("=").append(pagination.getIndex() - 1);
				paginationUrlParam.setBackUrl(sb.toString());
			}
			if (pagination.getLength() == pagination.getSize()) {
				sb = new StringBuffer().append(url);
				sb.append("&").append(PAGINATION_INDEX).append("=").append(pagination.getIndex() + 1);
				paginationUrlParam.setNextUrl(sb.toString());
			}
			sb = null;
		}
		return paginationUrlParam;
	}
}
